package com.ksyun.campus.client.util;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class ZkUtil {
    private CuratorFramework client;
    private PathChildrenCache cache;
    private String zookeeperConnectionString = "localhost:2181"; // zookeeper的连接字符串
    private String pathToWatch = "/metaService"; // 需要监听的路径

    @PostConstruct
    public void postCons() throws Exception {
        // 初始化与 Zookeeper 的连接
        client = CuratorFrameworkFactory.builder()
                .connectString(zookeeperConnectionString)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();

        client.start();
        // 监听配置变化
        cache = new PathChildrenCache(client, pathToWatch, true);
        cache.start();

        cache.getListenable().addListener((client, event) -> {
            switch (event.getType()) {
                case CHILD_ADDED:
                case CHILD_UPDATED:
                case CHILD_REMOVED:
                    // 处理节点变化，可以更新 cached IP 地址或其他配置
                    System.out.println("Node changed: " + event.getData().getPath());
                    break;
            }
        });
    }

    @PreDestroy
    public void cleanUp() throws Exception {
        // 关闭连接，清理资源
        if (cache != null) {
            cache.close();
        }
        if (client != null) {
            client.close();
        }
    }

    // 用于返回当前的 MetaService IP 地址
    public String getMetaServiceIp() throws Exception {
        // 从 Zookeeper 中读取当前的 MetaService IP 地址
        byte[] data = client.getData().forPath(pathToWatch);
        return new String(data);
    }
}
